package com.lanou3g.k12.service.impl;

import com.lanou3g.k12.entity.CouponCode;
import com.lanou3g.k12.mapper.CouponCodeMapper;
import com.lanou3g.k12.service.CouponCodeService;
import com.lanou3g.k12.utils.CodeRandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class CouponCodeServiceImpl implements CouponCodeService {

    @Autowired
    private CouponCodeMapper couponCodeMapper;

    /**
     * @param count 为库存量
     * @param status 码的状态
     * @param cpId 兑换券ID
     */
    //添加兑换码
    @Transactional
    @Override
    public void add(Integer count, Integer status, Long cpId) {
        //生成时间，存到数据库里
        Date date = new Date();
        //限制插入
        ArrayList<CouponCode> couponCodes = new ArrayList<>();
        //单次插入小于50,count1为变量,大于50,count1为常量,等于50

        Integer count1;
        if (count > 50) {
            count1 = 50;
        } else {
            count1 = count;
        }
        for (int i = 0; i < count1; i++) {
            CouponCode couponCode = new CouponCode();
            couponCode.setCreateTime(date);
            couponCode.setUpdateTime(date);
            couponCode.setCpId(cpId);
            couponCode.setStatus(status);
            String s = CodeRandomUtil.randomGenerate(10);
            couponCode.setCode(s);
            couponCodes.add(couponCode);
        }
        try {
            couponCodeMapper.add(couponCodes);
            count = count - 50;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count > 0) {
            add(count, status, cpId);
        }
    }

    /**
     *
     * @param cpId cpId 修改条件之一,为空的条件
     * @param array 要修改的兑换券码的id集合
     */
    @Override
    public void update(Long cpId,List<Long> array){
        //修改cpId为空的码
        couponCodeMapper.updateCode(cpId,array);
        //查询可用的兑换券码 先查询cpId存在的码

    }
    @Override
    public List<CouponCode> searchCode(){
        List<CouponCode> couponCodes = couponCodeMapper.searchCode();
        return couponCodes;
    }
}
